<template>
  <div class="main-todo">
    <input
      class="add-todo"
      type="text"
      placeholder="你想干啥?"
      autofocus
      v-model="content"
      @keyup.enter="handleAdd"
    />
    <!-- 父组件向子组件传参
      1. 在父组件的模板中绑定一个自定义的属性
      2. 在子组件的对象中通过props接收
     -->
    <todo-item
      v-for="item in filterData"
      :key="item.id"
      :todo="item"
      @remove="removeTodo"
      @toggle="handleToggle"
    ></todo-item>
    <!-- 清除已完成：父组件监听事件，调用删除接口 -->
    <todo-info
      :total="total"
      @toggle="handleChange"
      @del="handleDelCompleted"
    ></todo-info>
  </div>
</template>

<script>
//导入子组件
import TodoItem from './coms/TodoItem';

import TodoInfo from './coms/TodoInfo';

export default {
  name: 'MainTodo',
  components: {
    TodoItem,
    TodoInfo,
  },
  data() {
    return {
      todos: [],
      content: '',
      state: 'all',
    };
  },
  computed: {
    total() {
      // 根据todos数组计算所有'completed == 0'的结果
      // 使用数组的filter方法: 过滤出满足条件的元素，形成一个新数组
      return this.todos.filter((item) => item.completed == 0).length;
    },
    filterData() {
      switch (this.state) {
        case 'all':
          return this.todos;
        case 'active':
          return this.todos.filter((item) => item.completed == 0);
        case 'completed':
          return this.todos.filter((item) => item.completed == 1);
      }
    },
  },
  created() {
    // created生命周期函数在MainTodo组件被创建时自动执行
    // console.log('MainTodo被创建了...');
    this.getTodos();
  },
  methods: {
    getTodos() {
      // 发送ajax请求
      this.$http.get('http://localhost:3000/todos').then((res) => {
        console.log(res);
        // 解构res,只关心data中的数据
        const { data } = res;
        if (data.code == 0) {
          this.todos = data.result;
        }
      });
    },
    handleAdd() {
      // 判断内容不能为空
      if (this.content.trim() == '') {
        alert('请输入待办内容');
        return;
      }
      // 发送post请求
      this.$http
        .post('http://localhost:3000/todos', { content: this.content })
        .then((res) => {
          const { code, message, result } = res.data;
          if (code == 0) {
            // 重新获取数据
            this.getTodos();
            this.content = '';
          }
        });
    },
    handleToggle(id) {
      // 1.根据id查找对应的todos数组中的对象
      const data = this.todos.find((item) => item.id == id);
      // console.log(data);

      // 2.更新该对象的comleted的值
      data.completed == 0 ? (data.completed = 1) : (data.completed = 0);
      //console.log(data.completed);

      // 调用put接口，发送ajax请求
      this.$http.put(`http://localhost:3000/todos/${id}`, data).then((res) => {
        const { code, message, result } = res.data;
        if (code == 0) {
          this.getTodos();
        }
      });
    },
    removeTodo(v) {
      this.$http.delete('http://localhost:3000/todos/' + v.id).then((res) => {
        const { code, message, result } = res.data;
        if (code == 0) {
          this.getTodos();
        }
      });
    },
    handleChange(state) {
      this.state = state;
    },
    handleDelCompleted() {
      this.$http
        .delete('http://localhost:3000/todos?completed=1')
        .then((res) => {
          const { code } = res.data;
          if (code == 0) {
            this.getTodos();
          }
        });
    },
  },
};
</script>

<style lang="stylus">
// 引入mixin文件
@import '~styles/mixins.styl';

.main-todo
  width 600px
  min-width 600px
  margin 0 auto
  background-color #fff
  box-shadow 0 0 5px #666
  .add-todo
    padding 16px 16px 16px 36px
    font-size 24px
    font-family inherit
    font-weight 200
    clearDefault()
</style>
